﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using Demo.Model.Utils;
using log4net;
using Pampa.GenericEntity;
using Pampa.MVC.Helpers;

namespace Pampa.MVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            // Initializing Pampa
            PampaMvc.InitializeUsingCastleActiveRecords();
            
            // Configuración de ActiveRecord
            InitActiveRecord();

            // Crea el schema de base de datos a partir de los objetos de negocio
            ActiveRecordStarter.DropSchema();
            ActiveRecordStarter.CreateSchema();

            // entities
            DataManager.FillDemoData();

            // generic entities
            var genericEntityDataManager = new GenericEntityDataManager("Demo");
            genericEntityDataManager.CreateTables();
        }

        private void InitActiveRecord()
        {
            // Initializing ActiveRecord
            var source = ActiveRecordSectionHandler.Instance;
            var entities = Assembly.Load("Demo.Model");

            if (!ActiveRecordStarter.IsInitialized)
            {
                ActiveRecordStarter.Initialize(new[] { entities }, source);
            }
        }
    }
}